// request.js
import axios from 'axios';

// 创建axios实例
const rq = axios.create({
  baseURL: 'https://apifoxmock.com/m1/4840030-4495188-default', // 根地址
  timeout: 5000, // 超时时间
});

// 请求拦截器
rq.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，例如添加 token
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
rq.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.error('Response Error:', error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request Error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Error Setting Up Request:', error.message);
    }
    return Promise.reject(error);
  }
);

// 创建通用请求工具函数
function request(config: any) {
  const { url, method, data, params } = config;

  switch (method.toLowerCase()) {
    case 'get':
      return rq.get(url, { params });
    case 'post':
      return rq.post(url, data);
    case 'put':
      return rq.put(url, data);
    case 'delete':
      return rq.delete(url, { data });
    default:
      throw new Error(`Unsupported method: ${method}`);
  }
}

// 暴露出去
export default request;